package com.momei.security.handler;

import com.alibaba.fastjson.JSON;
import com.momei.common.entity.JsonResult;
import com.momei.common.utils.ResultTool;
import com.momei.security.MyUserDetails;
import com.momei.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *@description: 自定义退出处理类
 *@author: momo
 *@time: 2020/9/11
 */
@Component
public class MyLogoutSuccessHandlerImpl implements LogoutSuccessHandler
{

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException
    {
        MyUserDetails currentUser = (MyUserDetails) authentication.getPrincipal();
        redisUtils.delTokenFromRedis(currentUser.getUsername());
        JsonResult result = ResultTool.success();
        response.setContentType("text/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(result));
    }
}
